import 'dart:math';

import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/widgets/shadow/kq_box_decoration.dart';
import 'package:kq_flutter_core_widget/widgets/shadow/kq_box_shadow.dart';
import 'package:kq_flutter_pad_widgets/resources/kq_pad_theme_colors.dart';

import '../../resources/l10n/kq_pad_intl.dart';

/// 渐变分段评分滑动条
///
/// @author 周卓
class KqGradientSliderBar extends StatefulWidget {
  /// 默认值
  final double progress;

  /// 最小值
  final double min;

  /// 最大值
  final double max;

  /// 进度条高度
  final double? barHeight;

  /// 分段间隔颜色，默认
  final Color? gapColor;

  /// 渐变颜色值，从左到右
  final List<Color> gradientColors;

  /// 是否可以拖拽，默认不可拖拽，仅显示
  final bool dragEnable;

  /// 滑动监听，仅[dragEnable]=true时生效
  final Function(double progress)? onValueChanged;

  /// 进度指示器文本格式化，默认整数，如果需要显示小数，可以用这个格式化
  final String Function(double progress)? indicatorValueFormatter;

  const KqGradientSliderBar(
      {Key? key,
      this.min = 0,
      this.max = 100,
      this.barHeight,
      this.gapColor,
      this.dragEnable = false,
      this.indicatorValueFormatter,
      required this.gradientColors,
      this.progress = 0,
      this.onValueChanged})
      : super(key: key);

  @override
  KqGradientSliderBarState createState() => KqGradientSliderBarState();
}

class KqGradientSliderBarState extends State<KqGradientSliderBar> {
  double _progress = 0;

  double _indicatorLeft = 0;

  double _indicatorArrowOffset = 0;

  GlobalKey sliderKey = GlobalKey();

  @override
  void initState() {
    _progress = widget.progress;
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _calculateValue(widget.progress);
      setState(() {

      });
    });
    super.initState();
  }

  @override
  void didUpdateWidget(covariant KqGradientSliderBar oldWidget) {
    _progress = widget.progress;
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    _calculateValue(_progress);
    return Stack(
      children: [
        Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: EdgeInsets.only(left: _indicatorLeft, bottom: 2.dm),
              child: KqPadShadowPop(
                width: 25.dm,
                height: 17.dm,
                radius: 4.dm,
                arrowWidth: 4.5.dm,
                arrowHeight: 2.5.dm,
                arrowOffsetX: _indicatorArrowOffset,
                text: widget.indicatorValueFormatter?.call(_progress) ??
                    _progress.toStringAsFixed(0),
              ),
            ),
            Stack(
              clipBehavior: Clip.none,
              children: [
                Row(
                  children: [
                    Expanded(
                        child: Container(
                      height: widget.barHeight ?? 8.dm,
                      decoration: BoxDecoration(
                          gradient: LinearGradient(
                        colors: widget.gradientColors,
                      )),
                    )),
                  ],
                ),
                Positioned(
                    left: 0,
                    right: 0,
                    top: 0,
                    bottom: 0,
                    child: Row(
                      children: [
                        const Expanded(child: SizedBox()),
                        Container(
                          width: 4.dm,
                          color: KqPadThemeColors.tabBarBgColor,
                        ),
                        const Expanded(child: SizedBox()),
                        Container(
                          width: 4.dm,
                          color: KqPadThemeColors.tabBarBgColor,
                        ),
                        const Expanded(child: SizedBox()),
                        Container(
                          width: 4.dm,
                          color: KqPadThemeColors.tabBarBgColor,
                        ),
                        const Expanded(child: SizedBox()),
                        Container(
                          width: 4.dm,
                          color: KqPadThemeColors.tabBarBgColor,
                        ),
                        const Expanded(child: SizedBox()),
                      ],
                    )),
                Positioned(
                    left: 0,
                    right: 0,
                    top: 0,
                    bottom: 0,
                    child: Row(
                      children: [
                        Expanded(
                            child: SliderTheme(
                          data: SliderThemeData(
                              thumbShape: RoundSliderThumbShape(
                                  enabledThumbRadius: 4.dm,
                                  elevation: 0,
                                  pressedElevation: 0),
                              overlayShape:
                                  RoundSliderOverlayShape(overlayRadius: 4.dm)),
                          child: IgnorePointer(
                            ignoring: !widget.dragEnable,
                            child: Slider(
                              key: sliderKey,
                              value: _progress,
                              min: widget.min,
                              max: widget.max,
                              activeColor: Colors.transparent,
                              inactiveColor: Colors.transparent,
                              secondaryActiveColor: Colors.transparent,
                              thumbColor: Colors.white,
                              overlayColor:
                                  MaterialStateProperty.all(Colors.transparent),
                              onChanged: (value) {
                                setState(() {
                                  _progress = value;
                                  widget.onValueChanged?.call(value);
                                });
                              },
                            ),
                          ),
                        ))
                      ],
                    ))
              ],
            ),
            SizedBox(
              height: 2.dm,
            ),
            Row(
              children: [
                Expanded(
                  child: Text(
                    KqPadIntl.currentResource.low,
                    textAlign: TextAlign.start,
                    style: TextStyle(
                        fontSize: 7.dm, color: KqPadThemeColors.text59),
                  ),
                ),
                Expanded(
                  child: Text(
                    KqPadIntl.currentResource.mid,
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        fontSize: 7.dm, color: KqPadThemeColors.text59),
                  ),
                ),
                Expanded(
                  child: Text(
                    KqPadIntl.currentResource.high,
                    textAlign: TextAlign.end,
                    style: TextStyle(
                        fontSize: 7.dm, color: KqPadThemeColors.text59),
                  ),
                ),
              ],
            )
          ],
        )
      ],
    );
  }

  void _calculateValue(double value) {
    _progress = value;
    final RenderBox? overlay =
        sliderKey.currentContext?.findRenderObject() as RenderBox?;
    if (overlay == null) {
      return;
    }
    var widgetWidth = (overlay?.size.width ?? 1);
    var centerWidth = widgetWidth - 4.dm - 4.dm;
    var x = value * 1.0 / (widget.max) * (centerWidth) - (25.dm / 2.0) + 4.dm;
    _indicatorLeft = min(max(0, x), widgetWidth - 25.dm);
    _indicatorArrowOffset = x < 0
        ? x
        : x > widgetWidth - 25.dm
            ? (x - (widgetWidth - 25.dm))
            : 0;
  }
}

/// 带阴影和底部箭头的气泡
class KqPadShadowPop extends StatelessWidget {
  /// 宽度
  final double width;

  /// 高度
  final double height;

  /// 文本
  final String text;

  /// 圆角大小
  final double radius;

  /// 箭头宽度
  final double arrowWidth;

  /// 箭头高度
  final double arrowHeight;

  /// 箭头左右偏移量，默认0，代表中间，负数左移，正数右移
  final double arrowOffsetX;

  /// 文字距离上面的距离，默认2.r
  final double? textTop;

  const KqPadShadowPop({
    super.key,
    required this.width,
    required this.height,
    required this.text,
    required this.radius,
    required this.arrowWidth,
    required this.arrowHeight,
    this.textTop,
    this.arrowOffsetX = 0,
  });

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          decoration: KqBoxDecoration(boxShadow: [
            KqBoxShadow(
                offset: Offset(2.dm, 2.dm),
                blurRadius: 4.dm,
                spreadRadius: 0,
                color: const Color(0xffA6ABBD)),
            KqBoxShadow(
                offset: Offset(-2.dm, -2.dm),
                blurRadius: 4.dm,
                spreadRadius: 0,
                color: const Color(0xffFAFBFF)),
          ]),
          child: CustomPaint(
            size: Size(width, height),
            painter: KqPadShadowPopPainter(
                text,
                radius,
                KqPadThemeColors.tabBarBgColor,
                arrowWidth,
                arrowHeight,
                arrowOffsetX),
          ),
        ),
        Positioned(
          left: 0,
          right: 0,
          top: textTop ?? 2.dm,
          bottom: 0,
          child: Text(
            text,
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 7.dm, color: KqPadThemeColors.text26),
          ),
        )
      ],
    );
  }
}

class KqPadShadowPopPainter extends CustomPainter {
  final String text;
  final double borderRadius;
  final Color bgColor;
  final double arrowWidth;
  final double arrowHeight;

  // 箭头左右偏移量
  final double arrowOffsetX;

  KqPadShadowPopPainter(this.text, this.borderRadius, this.bgColor,
      this.arrowWidth, this.arrowHeight, this.arrowOffsetX);

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = bgColor
      ..isAntiAlias = true
      ..style = PaintingStyle.fill;

    final Path path = Path()
      // 左上角
      ..moveTo(0, borderRadius)
      ..lineTo(0, size.height - arrowHeight - borderRadius)
      // 左下角
      ..quadraticBezierTo(
          0, size.height - arrowHeight, borderRadius, size.height - arrowHeight)
      ..lineTo((size.width - arrowWidth) / 2 + arrowOffsetX,
          size.height - arrowHeight)
      // 箭头左边
      ..lineTo((size.width) / 2 + arrowOffsetX, size.height)
      // 箭头右边
      ..lineTo((size.width + arrowWidth) / 2 + arrowOffsetX,
          size.height - arrowHeight)
      ..lineTo(size.width - borderRadius, size.height - arrowHeight)
      // 右下角
      ..quadraticBezierTo(size.width, size.height - arrowHeight, size.width,
          size.height - arrowHeight - borderRadius)
      ..lineTo(size.width, borderRadius)
      // 右上角
      ..quadraticBezierTo(size.width, 0, size.width - borderRadius, 0)
      ..lineTo(borderRadius, 0)
      // 左上角
      ..quadraticBezierTo(0, 0, 0, borderRadius);

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
